# !/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
from functools import lru_cache, wraps
from pathlib import Path

from flask import Flask, jsonify
from flask_cors import CORS  # 导入 CORS 类

# 将项目的根目录添加到系统路径中
__project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(__project_root)

app = Flask(__name__)
CORS(app)  # 对应用启用 CORS，允许所有来源的跨域请求
# CORS(app, origins=["http://example.com"])  # 只允许来自 http://example.com 的跨域请求

# 定义文件根目录
ROOT_DIR = r'E:\WorkspaceFront\file-server\test_file_path'

# 缓存过期时间（秒），3 分钟
CACHE_EXPIRATION_TIME = 3 * 60


# 自定义带过期时间的缓存
def timed_lru_cache(seconds: int, maxsize: int = 128):
    def wrapper_cache(func):
        func = lru_cache(maxsize=maxsize)(func)
        func.lifetime = seconds
        func.expiration = time.time() + func.lifetime

        @wraps(func)
        def wrapped_func(*args, **kwargs):
            if time.time() >= func.expiration:
                func.cache_clear()
                func.expiration = time.time() + func.lifetime
            return func(*args, **kwargs)

        return wrapped_func

    return wrapper_cache


# @timed_lru_cache(seconds=CACHE_EXPIRATION_TIME)
def get_directory_content(path):
    if path.startswith('dist/'):
        path = path.replace('dist/', '')
    if path is None or path == '':
        full_path = Path(ROOT_DIR).as_posix()
    else:
        full_path = Path(os.path.join(ROOT_DIR, path)).as_posix()

    if not os.path.exists(full_path):
        return None

    if not os.path.isdir(full_path):
        return None

    rets = []
    list_files = os.listdir(full_path)
    if len(list_files) > 0:
        directories = []
        files = []
        for item in list_files:
            item_path = Path(os.path.join(full_path, str(item))).as_posix()
            relative_path = Path(item_path).relative_to(ROOT_DIR).as_posix()
            if os.path.isdir(item_path):
                item_name = os.path.basename(item_path)
                rets.append({
                    'fileType': 'dir',
                    'fileName': item_name,
                    'filePath': relative_path
                })
            else:
                item_name = os.path.basename(item_path)
                rets.append({
                    'fileType': 'file',
                    'fileName': item_name,
                    'filePath': relative_path
                })
        return rets
    return None


# 修改路由装饰器，将获取文件列表的路由改为 /api/files
@app.route('/api/files/', defaults={'path': ''})
@app.route('/api/files/<path:path>')
def get_file_list(path):
    if path.startswith('dist/'):
        path = path.replace('dist/', '')
    content = get_directory_content(path)
    if content:
        return jsonify(content)
    return "Directory not found", 404


# 新增一个路由 /api/file 用于获取文件内容
@app.route('/api/file/<path:path>')
def get_file_content(path):
    full_path = Path(os.path.join(ROOT_DIR, path)).as_posix()
    if not os.path.exists(full_path):
        return "File or directory not found", 404
    if os.path.isdir(full_path):
        return "The path is a directory, not a file", 400
    file_ext = str(os.path.basename(path)).split(".")[-1]
    if file_ext in ['png', 'jpg', 'jpeg', 'gif']:
        with open(full_path, 'rb') as f:
            file_bytes = f.read()
        return file_bytes, 200, {'Content-Type': f'image/{file_ext}'}
    elif file_ext in ['json', 'txt']:
        with open(full_path, 'r', encoding='utf-8') as f:
            file_content = f.read()
        return file_content, 200, {'Content-Type': 'application/json'}
    elif file_ext in ['xml']:
        with open(full_path, 'r', encoding='utf-8') as f:
            file_content = f.read()
        # 替换XML文档中所有的 > 和 <
        file_content = file_content.replace('<', '&lt;')
        file_content = file_content.replace('>', '&gt;')
        return file_content, 200, {'Content-Type': 'application/json'}
    else:
        with open(full_path, 'r', encoding='utf-8') as f:
            file_content = f.read()
        return file_content, 200, {'Content-Type': 'application/json'}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
